package com.sangmo.fts.process.factoring.service;

import com.sangmo.boot.framework.common.errors.ServiceException;
import com.sangmo.boot.framework.common.errors.StandardErrors;
import com.sangmo.boot.framework.plugin.dataview.crud.service.DelegateViewService;
import com.sangmo.boot.framework.plugin.dataview.crud.service.ViewService;
import com.sangmo.fts.process.factoring.interfaces.FfTransferApplyBankConfirmRequest;
import com.sangmo.fts.process.factoring.model.FfFactoringContract;
import com.sangmo.fts.process.factoring.model.FfTransferApply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class FfTransferApplyService extends DelegateViewService<FfTransferApply> {

    @Autowired
    private FfTransferApplyEntityService ffTransferApplyEntityService;

    @Autowired
    private FfFactoringContractService ffFactoringContractService;

    @Autowired
    private FfLoanService ffLoanService;

    @Override
    protected ViewService<FfTransferApply> getEntityService() {
        return ffTransferApplyEntityService;
    }

    public void submit(Long id) {
        FfTransferApply transferApply = this.get(id);
        if (null == transferApply.getApplyConfirmDoc()
                || null == transferApply.getInvoiceConfirmDoc()
                || null == transferApply.getTransferNoticeDoc()) {
            throw new ServiceException(StandardErrors.EXTERNAL_ERROR.getStatus(), "error.ffTransferApply.submit.permit.disabled");
        }
        transferApply.setState(FfTransferApply.States.SUBMITTED);
        this.save(transferApply);
    }

    public void bankConfirm(Long id, FfTransferApplyBankConfirmRequest request) {
        FfTransferApply transferApply = this.get(id);
        if (transferApply.isBankConfirm()) {
            throw new ServiceException(StandardErrors.EXTERNAL_ERROR.getStatus(), "error.ffTransferApply.bankConfirm.state.wrong");
        }
        transferApply.setCode(request.getCode());
        ffTransferApplyEntityService.bankConfirm(transferApply);
    }

    public void buyerConfirm(Long id) {
        FfTransferApply transferApply = this.get(id);
        if (transferApply.isBuyerConfirm()) {
            throw new ServiceException(StandardErrors.EXTERNAL_ERROR.getStatus(), "error.ffTransferApply.buyerConfirm.state.wrong");
        }
        ffTransferApplyEntityService.buyerConfirm(transferApply);
        FfFactoringContract contract = ffFactoringContractService.get(transferApply.getContractId());
        ffLoanService.transferApplyBuyerConfirm(contract.getLoanId());
    }

}
